<template>
  <div class="notice-view-container">
    <div class="page-header">
      <h2>系统通知查看</h2>
      <div class="header-content">
        <div class="search-container">
          <el-input
            v-model="searchQuery"
            placeholder="请输入通知标题"
            class="search-input"
            @keyup.enter="fetchNotices"
            clearable
          >
            <template #append>
              <el-button @click="fetchNotices" icon="Search"></el-button>
            </template>
          </el-input>
        </div>
        <el-select 
          v-model="filterType" 
          placeholder="通知类型" 
          clearable 
          @change="fetchNotices"
          style="width: 150px"
        >
          <el-option label="系统通知" value="system" />
          <el-option label="活动通知" value="activity" />
          <el-option label="提醒通知" value="reminder" />
        </el-select>
      </div>
    </div>

    <div class="notice-table">
      <el-table
        :data="filteredNotices"
        style="width: 100%"
        v-loading="loading"
      >
        <el-table-column prop="title" label="标题" min-width="150" />
        <el-table-column prop="content" label="内容" min-width="200">
          <template #default="scope">
            <el-tooltip
              effect="dark"
              :content="scope.row.content"
              placement="top"
              :show-after="500"
            >
              <span class="content-preview">{{ scope.row.content }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTagType(scope.row.type)">
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="readTime" label="阅读时间" width="160">
          <template #default="scope">
            {{ formatDate(scope.row.readTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="scope">
            <el-button
              size="small"
              type="primary"
              @click="handlePreview(scope.row)"
            >
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          layout="total, sizes, prev, pager, next, jumper"
          :background="true"
        />
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog
      v-model="showPreviewDialog"
      title="通知详情"
      width="500px"
    >
      <div class="notice-preview">
        <h3>{{ previewNotice.title }}</h3>
        <div class="notice-meta">
          <span>类型：{{ getTypeLabel(previewNotice.type) }}</span>
          <span>创建时间：{{ formatDate(previewNotice.createTime) }}</span>
           <span v-if="previewNotice.readTime">阅读时间：{{ formatDate(previewNotice.readTime) }}</span>
           <span v-if="previewNotice.status == 'read'">状态：已读</span>
          <span v-else>状态：未读</span>
        </div>
        <div class="notice-content">
          {{ previewNotice.content }}
        </div>
      </div>
     <template #footer>
    <span class="dialog-footer">
      <el-button @click="showPreviewDialog = false">关闭</el-button>
      <el-button 
        v-if="previewNotice.status === 'unread'" 
        type="primary" 
        @click="markAsRead"
        :loading="markingAsRead"
      >
        标记为已读
      </el-button>
    </span>
  </template>
</el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from '@/utils/request'
import { ElMessage } from 'element-plus'

const searchQuery = ref("")
const filterType = ref("")
const noticeList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)
const showPreviewDialog = ref(false)
const previewNotice = ref({})
const markingAsRead = ref(false)

// 过滤后的通知列表
const filteredNotices = computed(() => {
  let result = noticeList.value

  if (filterType.value) {
    result = result.filter(notice => notice.type === filterType.value)
  }
  if (searchQuery.value) {
    result = result.filter(notice => 
      notice.title && notice.title.toLowerCase().includes(searchQuery.value.toLowerCase())
    )
  }

  return result
})

// 获取通知类型标签样式
const getTypeTagType = (type) => {
  const types = {
    system: 'info',
    activity: 'success',
    reminder: 'warning'
  }
  return types[type] || 'info'
}

// 获取通知类型显示文本
const getTypeLabel = (type) => {
  const labels = {
    system: '系统通知',
    activity: '活动通知',
    reminder: '提醒通知'
  }
  return labels[type] || type
}

// 获取通知列表
const fetchNotices = async () => {
  loading.value = true
  try {
    const userId = localStorage.getItem('id') // Get the current user's ID from localStorage
    if (!userId) {
      ElMessage.error('请先登录')
      return
    }
    
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      title: searchQuery.value,
      type: filterType.value,
      userId: userId
    }
    
    const response = await axios.get(`/systemNotice/selectUserNoticeByUserId/${userId}`, { params })
    if (response.code === 200) {
      const pageData = response.data.List
      noticeList.value = pageData.list || []
      total.value = pageData.total
      currentPage.value = pageData.pageNum
      pageSize.value = pageData.pageSize
    }
  } catch (err) {
    ElMessage.error('获取通知列表失败')
    console.error(err)
  } finally {
    loading.value = false
  }
}

// 预览通知
const handlePreview = (notice) => {
  previewNotice.value = { ...notice }
  showPreviewDialog.value = true
}

// 格式化日期
const formatDate = (timestamp) => {
  if (!timestamp) return ''
  return new Date(timestamp).toLocaleString()
}

// 分页处理
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchNotices()
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1 // Reset to first page when changing page size
  fetchNotices()
}

const markAsRead = async () => {
  markingAsRead.value = true
  try {
    const response = await axios.put('/systemNotice/updateStatus', {
      notification_id: previewNotice.value.notificationId,
      status: 'read',
      readTime: new Date()
    })

    if (response.code === 200) {
      ElMessage.success('已标记为已读')
      // 更新当前预览通知的状态
      previewNotice.value.status = 'read'
      previewNotice.value.readTime = new Date()
      // 更新列表中的通知状态
      const notice = noticeList.value.find(n => n.notification_id === previewNotice.value.notification_id)
      if (notice) {
        notice.status = 'read'
        notice.readTime = previewNotice.value.readTime
      }
      // 重新获取通知列表
      await fetchNotices()
    }
  } catch (err) {
    ElMessage.error('标记失败')
    console.error(err)
  } finally {
    markingAsRead.value = false
  }
}
onMounted(() => {
  fetchNotices()
})
</script>

<style scoped>
.notice-view-container {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-top: 16px;
}

.search-container {
  width: 300px;
}

.notice-table {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 16px;
}

.content-preview {
  display: inline-block;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notice-preview {
  padding: 16px;
}

.notice-preview h3 {
  margin: 0 0 16px;
  color: #303133;
}

.notice-meta {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 16px;
  color: #909399;
  font-size: 14px;
}

.notice-content {
  line-height: 1.6;
  color: #606266;
  white-space: pre-line;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
